package model

import (
	"ginTea/structs"
	"ginTea/utils/errmsg"
	"ginTea/utils/helpers"
	"time"

	"github.com/jinzhu/gorm"
)

type Carousel struct {
	ID        uint      `gorm:"primary_key" json:"id"`
	CreatedAt time.Time `json:"created_at" gorm:"column:created_at;autoCreateTime"`
	UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at;autoCreateTime"`
	ImageUrl  string    `gorm:"column:image_url;not null" json:"image_url"`
	IsLocked  int       `gorm:"column:is_locked" json:"is_locked"`
	Desc      string    `gorm:"column:desc" json:"desc"`
}

// 新增轮播图
func CreateCarousel(data *Carousel) int {
	err := db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR
	} else {
		return errmsg.SUCCESS
	}
}

// 删除轮播图
func DeleteCarousel(id int) int {
	var data Carousel
	db.Select("id").Where("id=?", id).First(&data)
	if data.ID > 0 {
		err := db.Unscoped().Where("id = ?", id).Delete(&data).Error
		if err != nil {
			return errmsg.ERROR
		}
		return errmsg.SUCCESS
	}
	return errmsg.ERROR_CAROUSEL_NOT_EXIST
}

/*
获取所有轮播图
pageNum 当前页号
pageSize当前页大小
*/
func GetCarouselList(page int, pageSize int) structs.JSONResponse {
	var carousel []Carousel
	var total int
	var list []interface{}
	db.Find(&carousel).Count(&total)
	err := db.Order("id desc").
		Limit(pageSize).
		Offset((page - 1) * pageSize).
		Find(&carousel).
		Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return helpers.Error("")
	}
	for _, v := range carousel {
		list = append(list, v)
	}
	pageData := structs.NewPageData(list, pageSize, page, total)
	response := helpers.Success(pageData)
	return response
}

// 获取轮播图详情
// func GetCarouselInfo(id int) ([]Carousel, int) {
// 	var CarouselInfo []Carousel
// 	err := db.Preload("Category").Where("id=?", id).First(&CarouselInfo).Error
// 	if err != nil && err != gorm.ErrRecordNotFound {
// 		return nil, errmsg.ERROR_Carousel_NOT_EXIST
// 	}
// 	return CarouselInfo, errmsg.SUCCESS
// }

// 编辑轮播图
func UpdateCarousel(id int, data *Carousel) int {
	var Carousel Carousel
	var maps = make(map[string]interface{})
	maps["image_url"] = data.ImageUrl
	maps["is_locked"] = data.IsLocked
	maps["desc"] = data.Desc
	err := db.Model(&Carousel).Where("id = ?", id).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
